package concurrentpractice;

import com.google.common.collect.Lists;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import org.junit.Test;

public class CyclicBarrierSolution {

  @Test
  public void verifyCyclicBarrier() throws InterruptedException {
    List<String> temp = Lists.newArrayList();

    Runnable barrierAction = () -> {
      Collections.sort(temp);
      temp.forEach(System.out::print);
      temp.clear();
    };

    CyclicBarrier cyclicBarrier = new CyclicBarrier(2, barrierAction);

    Thread numberPrintThread = new Thread(() -> {
      for (int i = 1; i < 52; i = i + 2) {
        for (int j = 0; j < 2; j++) {
          temp.add(String.valueOf(i + j));
        }
        try {
          cyclicBarrier.await();
        } catch (InterruptedException | BrokenBarrierException e) {
          e.printStackTrace();
        }
      }
    });
    Thread letterPrintThread = new Thread(() -> {
      for (char i = 'A'; i <= 'Z'; i++) {
        temp.add(String.valueOf(i));
        try {
          cyclicBarrier.await();
        } catch (InterruptedException | BrokenBarrierException e) {
          e.printStackTrace();
        }
      }
    });

    numberPrintThread.start();
    letterPrintThread.start();

    numberPrintThread.join();
    letterPrintThread.join();
  }
}
